package sms

import (
	"gitee.com/iece/common/errorx"
	"gitee.com/iece/common/log"
	smsApi "github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

var smsSignName string
var accessKeyId string
var accessKeySecret string

func SetConf(signName, keyId, keySecret string) {
	smsSignName = signName
	accessKeyId = keyId
	accessKeySecret = keySecret
}

func SendSMS(phone string, templateCode string, param string) (err error) {
	if smsSignName == "" {
		return errorx.NewParamError("签名不能为空")
	}

	if accessKeyId == "" || accessKeySecret == "" {
		return errorx.NewParamError("缺少key信息")
	}

	if param == "" {
		return errorx.NewParamError("短信模版参数异常")
	}
	client, err := smsApi.NewClientWithAccessKey("cn-hangzhou", accessKeyId, accessKeySecret)
	if err != nil {
		return err
	}

	request := smsApi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.TemplateCode = templateCode
	request.TemplateParam = param
	request.SignName = smsSignName
	request.PhoneNumbers = phone

	rsp, err := client.SendSms(request)
	if err != nil {
		return err
	}
	if !rsp.IsSuccess() {
		return errorx.NewError(10000, rsp.Message)
	}

	log.Info("send phone captcha success...")
	return nil
}
